package com.sdsy.blockchaintrainingback.utils;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * @Description TODO
 * @Author linzili
 * @Date 2023/9/25 14:36
 * @Version 1.0
 */
@Component
public class JwtUtil {

    private  static String SECRET ;

    @Value("${jwt.secret}")
    private void setSecret(String secret) {
        JwtUtil.SECRET = secret;
    }

    /**
     * 生成令牌
     *
     * @param claims
     * @return
     */
    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, SECRET).compact();
    }

    public static boolean verifyToken(String token) {
        try {
             Jwts.parserBuilder()
                    .setSigningKey(SECRET)
                    .build()
                    .parseClaimsJws(token);

        }catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     * 解析令牌
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        return  Jwts.parserBuilder().setSigningKey(SECRET).build().parseClaimsJws(token).getBody();
    }
}
